package com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.message;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.Message;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.OutMessage;
import com.sanri.tools.modules.mock.l7.websocket.chat.service.ws.ChatSupport;
import lombok.Data;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component("chat/message")
public class ChatSocketMessageHandler implements SocketMessageCommand.MessageHandler {
    @Autowired
    private ChatSupport chatSupport;

    @Override
    public void handle(WebSocket conn, String message) throws IOException {
        ChatRequestMessage chatRequestMessage = JSON.parseObject(message, ChatRequestMessage.class);
        Message chat = chatRequestMessage.getMessage();
        chatSupport.sendMessage(chat);
    }

    /**
     * 收到客户端消息
     */
    @Data
    public static final class ChatRequestMessage {
        private String command;
        private Message message;

        public ChatRequestMessage() {
            this.command = "chat/message";
        }

        public ChatRequestMessage(Message message) {
            this.command = "chat/message";
            this.message = message;
        }
    }

    /**
     * 响应给客户端 websocket 消息
     */
    @Data
    public static final class ChatReponseMessage{
        private String command;
        private OutMessage message;

        public ChatReponseMessage() {
            this.command = "chat/message";
        }

        public ChatReponseMessage(OutMessage message) {
            this.command = "chat/message";
            this.message = message;
        }
    }
}
